package org.scs.carleton.ca.pgdt.pdt.layer.wrapper;

import java.util.List;
import java.util.Map;

import org.cs3.pdt.runtime.PrologRuntimePlugin;
import org.cs3.pl.prolog.PrologException;
import org.cs3.pl.prolog.PrologInterface;
import org.cs3.pl.prolog.PrologInterfaceException;
import org.cs3.pl.prolog.PrologSession;
import org.scs.carleton.ca.pgdt.pdt.layer.IPrologSession;

/**
 * A Wrapper for PDT's Session
 * 
 * @author tessierj
 */
public class PrologSessionWrapper implements IPrologSession {
	private PrologSession pdtPrologSession; // The tie-in
	private PrologInterface pdtPrologInterface; //Another tie-in
	
	public PrologSessionWrapper(String sessionId) throws PrologQueryException {
		pdtPrologInterface = PrologRuntimePlugin.getDefault().getPrologInterface(sessionId);
		try {
			pdtPrologInterface.start();
			pdtPrologSession = pdtPrologInterface.getSession(PrologInterface.NONE);
		}
		catch (PrologInterfaceException e) {
			throw new PrologQueryException(e);
		}
	}
	
	@Override
	public List<Map<String, Object>> queryAll(String query) throws PrologQueryException {
		try {
			return pdtPrologSession.queryAll(query);
		}
		catch (PrologException e) {
			throw new PrologQueryException(e);
		}
		catch (PrologInterfaceException e) {
			throw new PrologQueryException(e);
		}
	}

	@Override
	public List<Map<String, Object>> queryAll(String query, int flags) throws PrologQueryException {
		try {
			return pdtPrologSession.queryAll(query, flags);
		}
		catch (PrologException e) {
			throw new PrologQueryException(e);
		}
		catch (PrologInterfaceException e) {
			throw new PrologQueryException(e);
		}
	}

	@Override
	public Map<String, Object> queryOnce(String query) throws PrologQueryException {
		try {
			return pdtPrologSession.queryOnce(query);
		}
		catch (PrologException e) {
			throw new PrologQueryException(e);
		}
		catch (PrologInterfaceException e) {
			throw new PrologQueryException(e);
		}
	}

	@Override
	public Map<String, Object> queryOnce(String query, int flags) throws PrologQueryException {
		try {
			return pdtPrologSession.queryOnce(query, flags);
		}
		catch (PrologException e) {
			throw new PrologQueryException(e);
		}
		catch (PrologInterfaceException e) {
			throw new PrologQueryException(e);
		}
	}
	
	public void endSession() {
		try {
			pdtPrologInterface.stop();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
